import 'dart:math';
import 'dart:ui';

import 'package:fancy_shimmer_image/fancy_shimmer_image.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_overlay_loader/flutter_overlay_loader.dart';
import 'package:flutter_staggered_grid_view/flutter_staggered_grid_view.dart';
import 'package:loading_indicator/loading_indicator.dart';
import 'package:provider/provider.dart';
import 'package:qianyi/controller/homeTabController.dart';
import 'package:qianyi/controller/imageDetailUserController.dart';
import 'package:qianyi/entity/home/alumb_vo_list.dart';
import 'package:qianyi/entity/home/trendVo.dart';
import 'package:qianyi/entity/user_entity.dart';
import 'package:qianyi/network/http_entity.dart';
import 'package:qianyi/pages/home/community/page_view/like/mock.dart';
import 'package:qianyi/pages/home/mine/mock.dart';
import 'package:qianyi/utils/throttle.dart';
import 'package:qianyi/view_model/mine/user_view_model.dart';
import 'package:qianyi/wcao/kit/index.dart';
import 'package:qianyi/wcao/ui/tag.dart';
import 'package:qianyi/wcao/ui/theme.dart';
import 'package:get/get.dart';
import 'package:shimmer_animation/shimmer_animation.dart';
import 'package:sliver_tools/sliver_tools.dart';

import '../../../../controller/imageDetailVideoController.dart';
import '../../../../entity/message/Message.dart';
import '../../../../entity/mine/User.dart';
import '../../../../network/http_config.dart';
import '../../../../network/http_manager.dart';
import '../../../../state/token.dart';
import '../../../../ui/sliverAppBar/animation/animation_enum.dart';
import '../../../../ui/sliverAppBar/sliver_adsorption/sliver_adsorption_appbar.dart';
import '../../../../view_model/detail/AlbumViewMine.dart';
import '../../../../view_model/detail/ColloectionMine.dart';
import '../../../../view_model/detail/TrendViewUserPage.dart';
import '../../../../view_model/mine/trend_view_user_model.dart';



class OtherPageViewMine extends StatefulWidget {
  const OtherPageViewMine({Key? key}) : super(key: key);

  @override
  State<OtherPageViewMine> createState() => _PageViewMineState();
}

/// TODO: NestedScrollView 如何实现上拉加载，下拉刷新

class _PageViewMineState extends State<OtherPageViewMine> with AutomaticKeepAliveClientMixin ,TickerProviderStateMixin {
  TokenController tokenController = Get.find();
  ScrollController controller = ScrollController();
  ImageDetailUserController imageDetailUserController = Get.find();
  final List<String> tabs = ["动态", "专辑","收藏"];
  final PageController _pageController = PageController(initialPage: 1);
  bool isLoad = false;
  bool isFllow = false;
  String avatar = '';
  HomeTabController homeTabController = Get.find();
  User? user;
  @override
  void initState() {
    // SystemChrome.setEnabledSystemUIMode(SystemUiMode.manual, overlays: []);
    // TODO: implement initState
    super.initState();
    watiUser();
    isFllowUser();
  }
  isFllowUser() async {

    Map<String,dynamic> params = {
      "uid": tokenController.uid,
      "fid": imageDetailUserController.userId
    };
    HttpEntity httpEntity = await HttpManager.getInstance().request(url: '/platform/follow/isFollow',method: Method.get,params: params) as HttpEntity;
    setState(() {
      this.isFllow = httpEntity.getOriData()['data'];
    });
  }
  watiUser() async{
    user = imageDetailUserController!.user.value.last;

    String preAvatar = user!.avatar!;
    String preCover = user!.cover!;

    Map<String,String> params = {
      "path": preAvatar
    };
    HttpEntity httpEntity = await HttpManager.getInstance().request(url: '/util/fileoss/getFileUrl',params: params,method: Method.get) as HttpEntity;
    this.avatar = httpEntity.getOriData()['data'];
    Map<String,String> params1 = {
      "path": preCover
    };
    HttpEntity httpEntity1 = await HttpManager.getInstance().request(url: '/util/fileoss/getFileUrl',params: params1,method: Method.get) as HttpEntity;

    setState(() {
      isLoad = true;
    });
  }
  @override
  Widget build(BuildContext context) {
    return !isLoad? Shimmer(
      duration: Duration(seconds: 3), //Default value
      interval: Duration(seconds: 5), //Default value: Duration(seconds: 0)
      color: Colors.grey, //Default value
      colorOpacity: 0.3, //Default value
      enabled: true, //Default value
      direction: ShimmerDirection.fromLTRB(),  //Default Value
      child: Container(
        color: Colors.white,
      ),
    ):DefaultTabController(
      length: tabs.length,
      child: Scaffold(

        body: SliverAdsorptionAppbar(

          animationEnum: AnimationEnum.upToDown,
          controller: controller,
          collapsedColors: Colors.white,
          collapsedHeight: 100,
          expandedHeight: 300,
          expandedWidget: Container(

            padding: const EdgeInsets.only(top: 10, left: 10, right: 10),

            decoration: BoxDecoration(
              gradient: LinearGradient(
                begin: Alignment.topCenter,
                end: Alignment.bottomCenter,
                colors: [
                  Colors.grey[50]!,
                  Colors.blue[50]!,
                ],
              ),
            ),
            // color: Colors.blueGrey.withOpacity(.03),
            child: ListView(
              children: [

                ClipRRect(
                  borderRadius: BorderRadius.circular(10), // 设置圆角的大小
                  child: Container(
                    width: 70,
                     height: kIsWeb? 150:120,


                    child: FancyShimmerImage(
                      boxDecoration: BoxDecoration(
                        border: Border.all(
                          color: Colors.white, // 设置边框颜色
                          width: 2, // 设置边框宽度
                        ),
                        borderRadius: BorderRadius.circular(10), // 设置圆角的大小，与ClipRRect的圆角大小保持一致
                      ),
                      imageUrl: "${tokenController.cover.value}",
                    ),
                  ),
                )

                ,
                Row(
                  children: [
                    ClipRRect(
                      borderRadius: BorderRadius.circular(40),
                      child: FancyShimmerImage(

                        width: 70,
                        height: 70, imageUrl: "${avatar}",
                      ),
                    ),
                    const SizedBox(width: 10),
                    Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Text(
                          "${user!.username}",
                          style: TextStyle(fontSize: 18),
                        ),
                        SizedBox(height: 5),
                        Text(
                          "id号：${user!.id?.substring(5,15).toString()}",
                          style: TextStyle(color: Colors.black45),
                        ),
                      ],
                    ),
                    const Spacer(),
                    Column(
                      children: [
                        GestureDetector(
                          onTap: (){
                            Message item = Message(
                                sendId: imageDetailUserController.userId,
                                acceptId: tokenController.uid,
                                username: '',
                                avatar: '',
                                count: 0,
                                content: '',
                                date: '',
                                time: ''

                            );
                            homeTabController.messageItem = item;

                            Map<String, dynamic> params3 = {
                              "sendId":imageDetailUserController.userId,
                              "acceptId": tokenController.uid
                            };
                            HttpManager.getInstance().request(url: '/platform/chat/updateRecordCount',method: Method.get,params: params3) ;


                            Get.toNamed('/message/chat');
                          },
                          child: Icon(
                              Icons.comment,
                              color: WcaoTheme.placeholder

                          )
                        )
                        ,
                        GestureDetector(
                          onTap: (){
                            if(tokenController.uid == imageDetailUserController.userId) {

                              return;
                            }
                            HudUtil.showBeautiful(context);
                            Map<String,dynamic> params = {
                              "uid": tokenController.uid,
                              "fid": imageDetailUserController.userId
                            };
                            HttpEntity httpEntity;
                            HttpManager.getInstance().request(url: '/platform/follow/followUser',method: Method.post,params: params).then((res)=>{
                              httpEntity = res as HttpEntity,
                              this.isFllow = !this.isFllow,
                              HudUtil.dismiss()
                            });
                            setState(() {

                            });
                          },
                          child: Container(
                            width: 60,
                            height: 30,
                            padding: EdgeInsets.all(0.0), // 内边距
                            decoration: BoxDecoration(
                              border: Border.all(
                                color: WcaoTheme.primary, // 边框颜色
                                width: 0.5, // 边框宽度
                              ),
                              borderRadius: BorderRadius.circular(14.0), // 圆角大小
                            ),
                            child: ConstrainedBox(
                              constraints: BoxConstraints(

                              ),
                              child: Center(
                                child: Text(
                                  isFllow? "已关注":"关注",
                                  textAlign: TextAlign.center, // 文本居中
                                  style: TextStyle(fontSize: 14.7,color: WcaoTheme.primary), // 文本样式
                                ),
                              ),
                            ),
                          )
                        )
                        ,
                      ],
                    ),
                  ],
                ),
                // const SizedBox(height: 10),
                Text(
                  "个性签名：${imageDetailUserController.user.value.first.description == null?'还没有简介':imageDetailUserController.user.value.first!.description}",
                  style: TextStyle(fontSize: 14, color: Colors.black38),
                ),
                // const SizedBox(height: 10),
                Row(
                  children: [
                    Padding(padding: EdgeInsets.all(10),child: Column(
                      children: [
                        Obx(()=>

                            Text('${imageDetailUserController.user.value.first!.fanCount}'),

                        ),
                        Text('关注')
                      ],
                    ))
                    ,
                    Padding(padding: EdgeInsets.all(10),child: Column(
                      children: [
                        Obx(()=>

                            Text('${imageDetailUserController.user.value.first!.followCount}'),

                        ),
                        Text('粉丝')
                      ],
                    ))
                    ,
                    Padding(padding: EdgeInsets.all(10),child: Column(
                      children: [
                        Obx(()=>

                            Text('${imageDetailUserController.user.value.first!.trendCount}'),

                        ),
                        Text('动态')
                      ],
                    ))

                  ],
                ),

                // const Text(
                //   "我的相册：",
                //   style: TextStyle(fontSize: 14, color: Colors.black38),
                // ),
                // const SizedBox(height: 10),
                // SizedBox(
                //   height: 140,
                //   child: ListView(
                //     scrollDirection: Axis.horizontal,
                //     children: [
                //       ClipRRect(
                //         borderRadius: BorderRadius.circular(3),
                //         child: Image.network(
                //           "http://m.qpic.cn/psc?/V13kbO6L0KTqJm/bqQfVz5yrrGYSXMvKr.cqSKDpWMyZO2dUAYR8o62CXAzQZo.y5p1duZz4pNA4PlQvl7P9ITFRCtIVjtH*g1GDSu9mRSfHuyPDcxLtPlZAuQ!/b&bo=OQdABjkHQAYBJwA!&rf=viewer_4",
                //         ),
                //       ),
                //       const SizedBox(width: 10),
                //       ClipRRect(
                //         borderRadius: BorderRadius.circular(3),
                //         child: Image.network(
                //           "https://m.qpic.cn/psc?/V13kbO6L0KTqJm/LiySpxowE0yeWXwBdXN*SRad5Dx.*riskIwzt*GDBI6wJg6b2PBv8KDPQAQGW6hurmyvmtKTRb86C9VSarCVTRlpd4P1yjq4bsQzBREyLpw!/b&bo=OQdABjkHQAYBByA!&rf=viewer_4",
                //         ),
                //       ),
                //       const SizedBox(width: 10),
                //       ClipRRect(
                //         borderRadius: BorderRadius.circular(3),
                //         child: Image.network(
                //           "http://m.qpic.cn/psc?/V13kbO6L0KTqJm/bqQfVz5yrrGYSXMvKr.cqa8Sw.0xqGNfx3wgAeQhWrNh.a.P.OXZNe92fmN5ZTLMXAPekcFjFsXQhIiYLhm3H0IuJf*Yl.KkeMSDIywfO8E!/b&bo=QAZLCUAGSwkBFzA!&rf=viewer_4",
                //         ),
                //       ),
                //     ],
                //   ),
                // ),
              ],
            ),
          ),

          collapsedWidget: Padding(
            padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 5),
            child:  Row(
              children: [
                ClipRRect(
                  borderRadius: BorderRadius.circular(40),
                  child: Image.network(
                    "${avatar}",
                    width: 70,
                    height: 70,
                  ),
                ),
                const SizedBox(width: 10),
                Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text(
                      "${tokenController.user!.value[0].username}",
                      style: TextStyle(fontSize: 18),
                    ),
                    SizedBox(height: 5),
                    Text(
                      "id号：${tokenController.user!.value[0].id?.substring(5,15).toString()}",
                      style: TextStyle(color: Colors.black45),
                    ),
                  ],
                ),
                const Spacer(),
                Column(
                  children: [
                    Icon(Icons.edit_calendar_outlined, color: Colors.black38),
                    Text(
                      "编辑",
                      style: TextStyle(color: Colors.black26, fontSize: 12),
                    ),
                  ],
                ),
              ],
            ),

          ),
          slivers: [
            SliverAppBar(
              primary: false,
              toolbarHeight: 0,
              pinned: true,
              // backgroundColor: Colors.transparent,
              bottom: TabBar(
                indicatorColor: WcaoTheme.primary,
                indicatorSize: TabBarIndicatorSize.tab,
                unselectedLabelColor: WcaoTheme.indexBootBarColor,
                unselectedLabelStyle: const TextStyle(fontWeight: FontWeight.normal),
                labelColor: WcaoTheme.indexBootBarActColor,
                labelStyle: TextStyle(
                  fontSize: 16,
                  fontWeight: FontWeight.bold,
                ),
                indicatorWeight: 2,
                indicatorPadding: const EdgeInsets.symmetric(horizontal: 46),
                tabs: tabs
                    .map((e) => Tab(
                  text: e,
                ))
                    .toList(),
              ),

            ),
            // SliverList(
            //   delegate: SliverChildBuilderDelegate(
            //         (c, i) {
            //       return Container(
            //         margin: const EdgeInsets.only(bottom: 10),
            //         color: Colors.blue,
            //         height: 100,
            //         child: Center(
            //           child: Text(
            //             "$i",
            //             style: const TextStyle(color: Colors.white, fontSize: 20),
            //           ),
            //         ),
            //       );
            //     },
            //     childCount: 50,
            //   ),
            // ),

            // SliverFillRemaining(
            //   child:
            //   TabBarView(
            //     children: [
            //       TrendViewUserPage(),
            //       AlbumViewMine(),
            //       ColloectionMine(),
            //     ],
            //   ),
            // )
            //  SliverToBoxAdapter(
            //   child: Container(
            //     child: TabBarView(
            //       children: [
            //         TrendViewUserPage(),
            //         AlbumViewMine(),
            //         ColloectionMine(),
            //       ],
            //     ),
            //   ),
            // ),
          ], bodyT:
        TabBarView(
          children: [
            ImageTrendViewUserPage(),
            ImageAlbumViewMine(),
            ImageImageColloectionMine(),
          ],
        ),


        )

        ,

      ),
    );




  }

  @override
  // TODO: implement wantKeepAlive
  bool get wantKeepAlive => true;

  double getRandomHeight() {
    // 生成一个随机高度
    double height = Random().nextDouble() * (230 - 80) + 138;
    return   height ;
  }
  buildWateFall(TrendViewUserModel viewModel) {
    ImageDetailVideoController imageDetailVideoController = Get.find<ImageDetailVideoController>();
    return MasonryGridView.count(
      padding: EdgeInsets.all(2),
      // 展示几列
      crossAxisCount: 2,

      // 元素总个数
      itemCount: viewModel.datas.length,
      // 单个子元素
      itemBuilder: (BuildContext context, int index) {
        TrendEntity trendEntity = viewModel.datas[index];
        // var imgsUrl = jsonDecode(trendEntity.imgsUrl as String);
        return GestureDetector(
          onTap: () async {
            HudUtil.showBeautiful(context);
            String uid = await tokenController.getUid();
            Map<String,dynamic> params = {
              "mid":trendEntity.mid,
              "uid": uid
            };
            await HttpManager.getInstance().request(url: '/platform/browseRecord/addBrowseRecord',method: Method.post,params: params);
            imageDetailVideoController.imageDetailId.value = trendEntity.mid!;
            await imageDetailVideoController.getImageVideoDetail();
            // Loader.hide();
            HudUtil.dismiss();
            Get.toNamed("/ui/home/imageVideoDetail");

          },
          child: ClipRRect(
            borderRadius: BorderRadius.circular(4.0),
            child:  Column(
              children: [
                FancyShimmerImage(
                  height: getRandomHeight(),
                  imageUrl: trendEntity.cover!,
                ),
                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [

                    Flexible(

                      child: Text(
                        trendEntity.content as String,maxLines: 2,softWrap: true, // 允许文本在超出最大行数时以省略号结束
                        overflow: TextOverflow.ellipsis, style: TextStyle(fontWeight: FontWeight.w400),// 设置文本左对齐
                      ),

                    ),
                    Row(
                      children: [
                        Icon(
                          CupertinoIcons.heart,size: 14,
                          color: Colors.grey,),
                        Text(trendEntity.agreeCount as String)
                      ],
                    )



                  ],
                )

                ,


              ],
            ),
          ),
        );
      },

      // 纵向元素间距
      mainAxisSpacing: 5,
      // 横向元素间距
      crossAxisSpacing: 5,
      //本身不滚动，让外面的singlescrollview来滚动
      physics:const NeverScrollableScrollPhysics(),
      shrinkWrap: true, //收缩，让元素宽度自适应
    )

    //   WaterfallFlow.builder(
    //   padding: EdgeInsets.all(8.0),
    //   gridDelegate: SliverWaterfallFlowDelegateWithFixedCrossAxisCount(
    //     crossAxisCount: 2,
    //
    //     crossAxisSpacing: 5.0,
    //     mainAxisSpacing: 5.0,
    //   ),
    //   itemCount: viewModel.datas.length,
    //   itemBuilder: (BuildContext context, int index) {
    //     TrendEntity trendEntity = viewModel.datas[index];
    //     var imgsUrl = jsonDecode(trendEntity.imgsUrl as String);
    //     double height = getRandomHeight();
    //     return Container(
    //       // color: Colors.blue,
    //       height: height,
    //       child: Center(
    //         child: FancyShimmerImage(
    //           height: height-30,
    //           imageUrl: imgsUrl[0],
    //         ),
    //       ),
    //     );
    //   },
    // )
        ;


  }

  Widget createAddAlbum() {
    return Container(
      width: 50,
      height: 30,
      child:  MaterialButton(

        //背景颜色
        color: WcaoTheme.primary,
        //边框样式
        shape: const RoundedRectangleBorder(
          //边框颜色
          side: BorderSide(
            color: Colors.deepPurple,
            width: 1,
          ),
          //边框圆角
          borderRadius: BorderRadius.all(
            Radius.circular(8),
          ),
        ),
        //按钮高度
        height: 32,
        //按钮最小宽度
        minWidth: 60,
        //点击事件
        onPressed: () {},
        child: const Text(
          "查找",
          style: TextStyle(fontSize: 12, color: Colors.deepPurple),
        ),
      ),
    )
    ;

  }
}
